<template>
  <div class="app">
    <el-button class="addNew" @click="openMaterial" v-if="!billDia">记账</el-button>
    <el-tabs type="border-card" style="width: 100%;height: 100%" v-model="activeTab">
      <el-tab-pane label="按月查看" name="mouth">
        <el-calendar v-model="currentDate" :key="randomKey">
          <template slot="dateCell" slot-scope="{ data }">
            <div class="calendar-cell">
        <span :class="['calendar-day', { 'is-selected': isSelected(data.day) }]">
          {{ data.day.split('-').slice(2).join('-') }} {{ isSelected(data.day) ? '✔️' : '' }}
        </span>
              <div v-if="isSelected(data.day)" class="details">
                <div class="detail-card income" v-if="incomeData[data.day]">
                  收入：{{ incomeData[data.day] || '0' }}
                </div>
                <div class="detail-card expense" v-if="expenseData[data.day]">
                  支出：{{ expenseData[data.day] || '0' }}
                </div>
              </div>
            </div>
          </template>
        </el-calendar>
      </el-tab-pane>
      <el-tab-pane label="按年查看" name="year">
        <div class="main">
          <div v-for="b in billList" :key="b.year"> {{ b.year + '年:' }}
            <el-collapse accordion>
              <el-collapse-item v-for="(months, index) in b.month"
                                :title="getMonthTitle(months)"
                                :name="b.year + '-' + index"
                                :key="index">
                <el-timeline :key="randomKey">
                  <el-timeline-item v-for="c in getMonthData(months)"
                                    :timestamp="c.time.replaceAll('T',' ').replaceAll('.000Z',' ')"
                                    placement="top"
                                    :key="c.time">
                    <el-card>
                      类型:{{ c.name }}<br>
                      {{ c.type === '0' ? '支出' : '收入' }}:{{ c.price }} 元 <br>
                      备注:{{ c.remark }}<br>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </el-collapse-item>
            </el-collapse>
            <br><br>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="bill">
      <BillComponent
          :visible.sync="billDia"
          ref="billComponent"
      />
    </div>
  </div>
</template>

<script>
import BillComponent from './components/BillComponent.vue';
import axios from "@/Axios/axios";

export default {
  components: {
    BillComponent
  },
  data() {
    return {
      thisMouth: new Date().getMonth() + 1,
      billDia: false,
      billList: '',
      cardList: '',
      randomKey: Math.random(),
      activeTab: 'mouth',
      selectedDays: [],
      currentDate: new Date(),
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      currentDay: new Date().getDay(),
      incomeData: {},
      expenseData: {},
    }
  },
  methods: {
    openMaterial() {
      this.billDia = true;
      this.$refs.billComponent.billType(0);
    },
    select() {
      axios.get('/userBill/select').then(res => {
        let yearList = res.data;
        yearList.sort((a, b) => {
          if (a.year < b.year)
            return 1;
          if (a.year > b.year)
            return -1;
          return 0;
        });
        yearList.forEach(item => {
          item.month = item.month.sort((a, b) => {
            const monthA = parseInt(Object.keys(a)[0]);
            const monthB = parseInt(Object.keys(b)[0]);
            return monthB - monthA;
          });
          item.sortFlag = true;
        });
        this.billList = yearList;
      }).catch(() => {
      })
    },
    getMonthTitle(months) {
      return Object.keys(months)[0] + '月';
    },
    getMonthData(months) {
      const monthKey = Object.keys(months)[0];
      return months[monthKey];
    },
    getDaysForMonth() {
      let month = `${this.currentYear}-${this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth}`;
      this.selectedDays = [];
      axios.get(`/userBill/selectDaysForMonth/${month}`).then(res => {
        if (res.code === 200) {
          this.selectedDays = res.data.days;
          this.incomeData = res.data.incomeData;
          this.expenseData = res.data.expenseData;
          if (this.selectedDays.length > 0) {
            this.randomKey = Math.random();
          } else {
            this.$message.warning('本月没有记账');
          }
        } else {
          this.$message.error('获取数据失败');
        }
      }).catch(() => {
      });
    },
    isSelected(day) {
      const dayParts = day.split('-');
      const dayNumber = parseInt(dayParts[2], 10);
      const month = parseInt(dayParts[1], 10);
      const year = parseInt(dayParts[0], 10);
      const currentMonth = this.currentDate.getMonth() + 1;
      const currentYear = this.currentDate.getFullYear();
      return this.selectedDays.includes(dayNumber) && month === currentMonth && year === currentYear;
    },
  },
  mounted() {
    this.select();
    this.getDaysForMonth();
  },
  watch: {
    currentDate(newDate) {
      const date = new Date(newDate);
      this.currentYear = date.getFullYear();
      let month = this.currentMonth;
      this.currentMonth = date.getMonth() + 1;
      this.currentDay = date.getDate();
      if (month === null || month !== this.currentMonth) {
        this.getDaysForMonth();
      }
    }
  }
}
</script>

<style scoped>
.app {
  width: 100%;
}

.el-collapse-item:hover {
  background-color: #2d54a1 !important;
}

.el-tabs__content ::v-deep .el-tab-pane {
  width: 100%;
}

.main {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.addNew {
  position: fixed;
  border-radius: 50px;
  width: 80px;
  height: 80px;
  right: 10px;
  top: 70%;
  z-index: 999999;
  background-color: #a9e8f8;
  color: white;
}

.is-selected {
  color: #1989FA;
}

.calendar-day {
  cursor: default; /* 禁止鼠标点击效果 */
}


.calendar-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px;
}

.calendar-day {
  font-weight: bold;
  font-size: 14px;
}

.is-selected {
  color: #1989FA;
}

.details {
  margin-top: 8px;
  display: flex;
  gap: 5px;
  flex-direction: column;
}

.detail-card {
  padding: 3px 8px;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
  width: 80px;
}

.income {
  background-color: #e8f5e9;
  color: #388e3c;
}

.expense {
  background-color: #ffebee;
  color: #d32f2f;
}
</style>
